package kr.pe.johnkim.pushchat.mobile.controller;

import kr.pe.johnkim.pushchat.mobile.domain.PushChatDiary;
import kr.pe.johnkim.pushchat.mobile.service.PushChatDiaryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author : John_Kim <cale9797@gmail.com>
 * @date : 13. 7. 11.
 */
@Controller
@RequestMapping(value = "/pushChatDiaryController")
public class PushChatDiaryController {

    // SLF4J Logging
    private Logger logger = LoggerFactory.getLogger(PushChatDiaryController.class);

    @Autowired
    private PushChatDiaryService pushChatDiaryService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    // 다이어리 이미지 업로드 Directory.
    private @Value("${pushchat.upload.diary.image.directory}") String uploadDiaryImageDirectory;

    // 다이어리 이미지 업로드 URL.
    private @Value("${pushchat.upload.diary.image.url}") String uploadDiaryImageUrl;

    // 다이어리 썸네일 업로드 Directory.
    private @Value("${pushchat.upload.diary.thumbnail.directory}") String uploadDiaryThumbnailDirectory;

    // 다이어리 썸네일 업로드 URL.
    private @Value("${pushchat.upload.diary.thumbnail.url}") String uploadDiaryThumbnailUrl;

    /**
     * 일기를 등록 한다.
     *
     * @param pushChatDiary
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/registerDiary", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public PushChatDiary registerDiary(@RequestBody PushChatDiary pushChatDiary) throws Exception {
        logger.info("registerDiary");

        PushChatDiary result = new PushChatDiary();

        try {
            // 썸네일 경로를 공백으로 다시 세팅 한다.
            pushChatDiary.setThumbnailUrl("");

            this.pushChatDiaryService.registerDiary(pushChatDiary);
            result.setResult("SUCCESS");
            logger.info("success to register diary.");
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.error("fail to register diary.");
        }

        return result;
    }

    /**
     * 일기와 이미지를 등록 한다.
     *
     * @param memberId
     * @param category
     * @param subject
     * @param content
     * @param fileUrl
     * @param activateYn
     * @param modifyDate
     * @param registerDate
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/registerDiaryWithImage", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public PushChatDiary registerDiaryWithImage(
            @RequestParam("memberId") String memberId,
            @RequestParam("category") String category,
            @RequestParam("subject") String subject,
            @RequestParam("content") String content,
            @RequestParam("fileUrl") String fileUrl,
            @RequestParam("activateYn") String activateYn,
            @RequestParam("modifyDate") String modifyDate,
            @RequestParam("registerDate") String registerDate,
            @RequestParam("file")MultipartFile file
    ) throws Exception {
        logger.info("registerDiaryWithImage");

        PushChatDiary parameter = new PushChatDiary();

        parameter.setMemberId(memberId);
        parameter.setCategory(category);
        parameter.setSubject(subject);
        parameter.setContent(content);
        parameter.setFileUrl(fileUrl);
        parameter.setActivateYn(activateYn);
        parameter.setModifyDate(modifyDate);
        parameter.setRegisterDate(registerDate);

        PushChatDiary result = new PushChatDiary();

        try {
            if(!file.isEmpty()) {
                // 이미지 파일 경로를 다시 세팅 한다.
                String uploadDiaryImagePath = this.httpServletRequest.getSession().getServletContext().getRealPath("/") + uploadDiaryImageDirectory;
                logger.info("uploadDiaryImagePath : {}", uploadDiaryImagePath);
                parameter.setFileUrl(uploadDiaryImageUrl + file.getOriginalFilename());

                // 썸네일 파일 경로를 다시 세팅 한다.
                String uploadDiaryThumbnailPath = this.httpServletRequest.getSession().getServletContext().getRealPath("/") + uploadDiaryThumbnailDirectory;
                logger.info("uploadDiaryThumbnailPath : {}", uploadDiaryThumbnailPath);
                parameter.setThumbnailUrl(uploadDiaryThumbnailUrl + file.getOriginalFilename());

                // 일기와 이미지를 등록 한다.
                this.pushChatDiaryService.registerDiaryWithImage(parameter, uploadDiaryImagePath, uploadDiaryThumbnailPath, file);

                result.setResult("SUCCESS");
                logger.info("success to register diary with image.");
            } else {
                result.setResult("FAIL");
                logger.info("fail to register diary with image.");
            }
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.error("fail to register diary with image.");
        }

        return result;
    }

    /**
     * 일기를 수정 한다.
     *
     * @param pushChatDiary
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/updateDiary", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public PushChatDiary updateDiary(@RequestBody PushChatDiary pushChatDiary) throws Exception {
        logger.info("updateDiary");

        PushChatDiary result = new PushChatDiary();

        try {
            // 썸네일 경로를 공백으로 다시 세팅 한다.
            pushChatDiary.setThumbnailUrl("");

            this.pushChatDiaryService.updateDiary(pushChatDiary);
            result.setResult("SUCCESS");
            logger.info("success to update diary.");
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.error("fail to update diary.");
        }

        return result;
    }

    /**
     * 일기와 이미지를 수정 한다.
     *
     * @param idPushChatDiary
     * @param memberId
     * @param category
     * @param subject
     * @param content
     * @param fileUrl
     * @param activateYn
     * @param modifyDate
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/updateDiaryWithImage", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public PushChatDiary updateDiaryWithImage(
            @RequestParam("idPushChatDiary") String idPushChatDiary,
            @RequestParam("memberId") String memberId,
            @RequestParam("category") String category,
            @RequestParam("subject") String subject,
            @RequestParam("content") String content,
            @RequestParam("fileUrl") String fileUrl,
            @RequestParam("activateYn") String activateYn,
            @RequestParam("modifyDate") String modifyDate,
            @RequestParam("file")MultipartFile file
    ) throws Exception {
        logger.info("updateDiaryWithImage");

        PushChatDiary parameter = new PushChatDiary();

        parameter.setIdPushChatDiary(idPushChatDiary);
        parameter.setMemberId(memberId);
        parameter.setCategory(category);
        parameter.setSubject(subject);
        parameter.setContent(content);
        parameter.setFileUrl(fileUrl);
        parameter.setActivateYn(activateYn);
        parameter.setModifyDate(modifyDate);

        PushChatDiary result = new PushChatDiary();

        try {
            if(!file.isEmpty()) {
                // 이미지 파일 경로를 다시 세팅 한다.
                String uploadDiaryImagePath = this.httpServletRequest.getSession().getServletContext().getRealPath("/") + uploadDiaryImageDirectory;
                logger.info("uploadDiaryImagePath : {}", uploadDiaryImagePath);
                parameter.setFileUrl(uploadDiaryImageUrl + file.getOriginalFilename());

                // 썸네일 파일 경로를 다시 세팅 한다.
                String uploadDiaryThumbnailPath = this.httpServletRequest.getSession().getServletContext().getRealPath("/") + uploadDiaryThumbnailDirectory;
                logger.info("uploadDiaryThumbnailPath : {}", uploadDiaryThumbnailPath);
                parameter.setThumbnailUrl(uploadDiaryThumbnailUrl + file.getOriginalFilename());

                // 일기와 이미지를 수정 한다.
                this.pushChatDiaryService.updateDiaryWithImage(parameter, uploadDiaryImagePath, uploadDiaryThumbnailPath, file);

                result.setResult("SUCCESS");
                logger.info("success to update diary with image.");
            } else {
                result.setResult("FAIL");
                logger.info("fail to update diary with image.");
            }
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.error("fail to update diary with image.");
        }

        return result;
    }

    /**
     * 일기를 비활성화 한다.
     *
     * @param pushChatDiary
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/updateDeactivateDiary", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public PushChatDiary updateDeactivateDiary(@RequestBody PushChatDiary pushChatDiary) throws Exception {
        logger.info("updateDeactivateDiary");

        PushChatDiary result = new PushChatDiary();

        try {
            this.pushChatDiaryService.updateDeactivateDiary(pushChatDiary);
            result.setResult("SUCCESS");
            logger.info("success to update deactivate diary.");
        } catch (Exception e) {
            result.setResult("FAIL");
            logger.error("fail to update deactivate diary.");
        }

        return result;
    }

    /**
     * 일기 목록을 가져 온다.
     *
     * @param pushChatDiary
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/selectDiaryList", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public List<PushChatDiary> selectDiaryList(@RequestBody PushChatDiary pushChatDiary) throws Exception {
        logger.info("selectDiaryList");

        return this.pushChatDiaryService.selectDiaryList(pushChatDiary);
    }

    /**
     * 일기 상세 정보를 가져 온다.
     *
     * @param pushChatDiary
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/selectDiaryInformation", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public PushChatDiary selectDiaryInformation(@RequestBody PushChatDiary pushChatDiary) throws Exception {
        logger.info("selectDiaryInformation");

        return this.pushChatDiaryService.selectDiaryInformation(pushChatDiary);
    }

    /**
     * 내 일기 목록을 가져 온다.
     *
     * @param pushChatDiary
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/selectMyDiaryList", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public List<PushChatDiary> selectMyDiaryList(@RequestBody PushChatDiary pushChatDiary) throws Exception {
        logger.info("selectMyDiaryList");

        return this.pushChatDiaryService.selectMyDiaryList(pushChatDiary);
    }

    /**
     * 검색한 일기 목록을 가져 온다.
     *
     * @param pushChatDiary
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/selectSearchDiaryList", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public List<PushChatDiary> selectSearchDiaryList(@RequestBody PushChatDiary pushChatDiary) throws Exception {
        logger.info("selectSearchDiaryList");

        return this.pushChatDiaryService.selectSearchDiaryList(pushChatDiary);
    }
}
